@echo off
setlocal enabledelayedexpansion
cls
echo =====================================
echo   MyWallet - Clean Build
echo =====================================
echo.
echo This will:
echo   1. Kill all Java processes
echo   2. Clean all cache
echo   3. Get dependencies
echo   4. Build APK (3-5 minutes)
echo.
echo Use this for release builds or when you have issues.
echo.
echo Press any key to start...
pause >nul

cls
echo.
echo Clean Build Process...
echo.

echo [Step 1/6] Checking Flutter...
call flutter --version >nul 2>&1
if errorlevel 1 (
    echo.
    echo ERROR: Flutter not found!
    echo Please install Flutter and add to PATH
    echo.
    goto :error
)
echo OK
echo.

echo [Step 2/6] Killing Java processes...
taskkill /F /IM java.exe >nul 2>&1
taskkill /F /IM javaw.exe >nul 2>&1
echo OK
echo.
echo Waiting for processes to close...
timeout /t 3 /nobreak >nul
echo OK
echo.

echo [Step 3/6] Cleaning cache...
call flutter clean
if errorlevel 1 (
    echo ERROR: Clean failed!
    goto :error
)
echo OK
echo.

echo [Step 4/6] Getting dependencies...
call flutter pub get
if errorlevel 1 (
    echo ERROR: pub get failed!
    echo Please check network connection
    goto :error
)
echo OK
echo.

echo [Step 5/6] Building APK...
echo.
echo This will take 3-5 minutes...
echo.
echo Will generate 3 APK files:
echo   - app-armeabi-v7a-release.apk  (21MB)
echo   - app-arm64-v8a-release.apk    (25MB, recommended)
echo   - app-x86_64-release.apk       (27MB)
echo.
echo Building...
echo.

call flutter build apk --release --split-per-abi
if errorlevel 1 (
    echo.
    echo ERROR: Build failed!
    echo.
    echo Common issues:
    echo   1. Android SDK not installed
    echo   2. Network connection problem
    echo   3. Run: flutter doctor
    echo.
    goto :error
)

echo.
echo [Step 6/6] Opening folder...
if exist "build\app\outputs\flutter-apk" (
    echo.
    echo Generated APK files:
    for %%f in (build\app\outputs\flutter-apk\*.apk) do (
        set "size=%%~zf"
        set /a "sizeMB=!size! / 1048576"
        echo   [OK] %%~nxf  (!sizeMB! MB)
    )
    echo.
    start explorer build\app\outputs\flutter-apk
    echo OK
) else (
    echo WARNING: APK folder not found!
)
echo.

:success
echo.
echo =====================================
echo Build Complete!
echo =====================================
echo.
echo Location: build\app\outputs\flutter-apk\
echo.
echo Recommended: app-arm64-v8a-release.apk
echo.
echo Installation:
echo   Method 1: Copy to phone and install
echo   Method 2: adb install -r app-arm64-v8a-release.apk
echo.
echo Press any key to exit...
pause >nul
exit /b 0

:error
echo.
echo =====================================
echo Build Failed!
echo =====================================
echo.
echo Press any key to exit...
pause >nul
exit /b 1
